package com.ln.lnzw.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.blankj.utilcode.util.ActivityUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.ln.lnzw.R;
import com.ln.lnzw.activity.ConsultationReplyDetailsActivity;
import com.ln.lnzw.activity.UserAgreementActivity;
import com.ln.lnzw.adapter.AnnouncementAdapter;
import com.ln.lnzw.adapter.ConsultationReplyAdapter;
import com.ln.lnzw.app.AppConstant;
import com.ln.lnzw.base.BaseFragment;
import com.ln.lnzw.bean.ConsultationReplyBean;
import com.ln.lnzw.bean.WcmBean;
import com.ln.lnzw.net.HttpMethodString;
import com.ln.lnzw.net.HttpMethods;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by wuwei on 2018/5/9.
 * 咨询回复
 */

public class ConsultationReplyFragment extends BaseFragment {

    @BindView(R.id.recycler)
    RecyclerView recycler;
    Unbinder unbinder;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    private ConsultationReplyAdapter consultationReplyAdapter;
    private List<ConsultationReplyBean.ResultBean.ListBean> mList = new ArrayList<>();
    private int count = 1;
    private int lastSize;
    private int nowSize;
    private int delayMillis = 1000;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.consultationreplyfragment_activity, null);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        setView();
        initData();
    }

    private void setView() {
        recycler.setNestedScrollingEnabled(false);
        recycler.setLayoutManager(new LinearLayoutManager(activity));
        consultationReplyAdapter = new ConsultationReplyAdapter(R.layout.item_consultation_reply,mList);
        recycler.setAdapter(consultationReplyAdapter);
        refreshLayout.setDisableContentWhenRefresh(true);//是否在刷新的时候禁止列表的操作
        refreshLayout.setDisableContentWhenLoading(true);//是否在加载的时候禁止列表的操作
        recycler.addOnItemTouchListener(new OnItemClickListener() {

            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                Bundle b = new Bundle();
                Log.i("478", "onSimpleItemClick: "+mList.get(position).getId());
                b.putString("id", mList.get(position).getId());
                ActivityUtils.startActivity(b, activity, ConsultationReplyDetailsActivity.class);
            }
        });
        //设置下拉刷新监听事件
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull final RefreshLayout refreshLayout) {
                downRefresh();
            }
        });

        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull final RefreshLayout refreshLayout) {
                onLoadMoreRequested();
            }
        });
    }

    private void onLoadMoreRequested() {
        lastSize = mList.size();
        Log.i("478", "lastSize: ====="+lastSize);
        Log.i("478", "count: ====="+count);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                HttpMethods.getInstanceCenter().getInstanceCenter().info.getConsultationCeplyList(""+count,"10")
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Observer<ConsultationReplyBean>() {
                            @Override
                            public void onSubscribe(Disposable d) {

                            }

                            @Override
                            public void onNext(ConsultationReplyBean consultationReplyBean) {
                                if ("200".equals(consultationReplyBean.getCode())) {
                                    mList.addAll(consultationReplyBean.getResult().getList());
                                    nowSize = mList.size();
                                    Log.i("478", "nowSize: ====="+nowSize);
                                    if (nowSize>lastSize){
                                        double a=consultationReplyBean.getResult().getTotalCount();
                                        double b=consultationReplyBean.getResult().getPageSize();
                                        if (count>Math.ceil(a/b)){
                                            refreshLayout.finishLoadMoreWithNoMoreData();
                                        }
                                        count++;
                                    }else {
                                        refreshLayout.finishLoadMoreWithNoMoreData();
                                    }

                                }
                            }

                            @Override
                            public void onError(Throwable e) {
                                Log.i("489", "onError: "+e.toString());
                            }

                            @Override
                            public void onComplete() {
                                consultationReplyAdapter.notifyDataSetChanged();
                                refreshLayout.finishLoadMore();
                            }
                        });
            }
        }, delayMillis);

    }

    private void downRefresh() {
        count = 1;
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                refreshLayout.setNoMoreData(false);
                initData();
                refreshLayout.finishRefresh();
            }
        }, delayMillis);
    }

    private void initData() {
        HttpMethods.getInstanceCenter().getInstanceCenter().info.getConsultationCeplyList(count+"","10")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ConsultationReplyBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ConsultationReplyBean consultationReplyBean) {
                        if (mList != null) {
                            mList.clear();
                        }
                        if ("200".equals(consultationReplyBean.getCode())) {
                            mList.addAll(consultationReplyBean.getResult().getList());
                            double a = consultationReplyBean.getResult().getTotalCount();
                            double b = consultationReplyBean.getResult().getPageSize();
                            if (count < Math.ceil(a / b)) {
                                count = count + 1;
                            } else {
                                refreshLayout.finishLoadMoreWithNoMoreData();
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {
                        consultationReplyAdapter.notifyDataSetChanged();
                    }
                });

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
}
